﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading;
using System.Diagnostics;
namespace autotest {
    public class IOWiFi
    {
        private Socket IOSocket;
        private string IO_IP = "120.24.226.63";
        int IO_Port = 80;
        int counter = 0;
        private byte[] data = new byte[1024*8];
        private int msgind = 0;
        public void init(string ipaddress){
            IO_IP = ipaddress;
            Console.WriteLine("start the application");
            IOSocket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            IOSocket.SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.KeepAlive, true);

            IOSocket.ReceiveTimeout = 10000;
            IOSocket.SendTimeout = 10000;
            IOSocket.NoDelay = true;
            IOSocket.Connect(new IPEndPoint(IPAddress.Parse(IO_IP), IO_Port));
        }
        public string Heartbeaton(){
            string ret = "";
            string msg = "";
            Stopwatch st=new Stopwatch ();//实例化类
            try{
                st.Start();
                // msg = $"GET /ajax.php?a=get&t=all HTTP/1.1\r\n HOST:{IO_IP}\r\n\r\n";
                msg = $"GET /index.html HTTP/1.1\r\n HOST:{IO_IP}\r\n\r\n";
                if ((msgind % 3) == 1){
                   // msg = $"GET /ajax.php?a=save&t=var&var_0000=0 HTTP/1.1\r\n HOST:{IO_IP}\r\n\r\n";
                }else if((msgind % 3) == 2){
                    //msg = $"GET /ajax.php?a=save&t=var&var_0000=1 HTTP/1.1\r\n HOST:{IO_IP}\r\n\r\n";
                }
                msgind++;
                byte[] IO_v = Encoding.ASCII.GetBytes(msg);
                
                IOSocket.Send(IO_v);
                var tempmsg = IOSocket.Receive(data);
                st.Stop();
                ret = st.ElapsedMilliseconds.ToString();
            }
            catch (Exception ex){
                IOSocket?.Close();
                IOSocket?.Dispose();
                ret = "error: disconnection";
            }
            return(ret);
           
        }
    }
}